package com.sam.im.heiqun.uis.activities;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.MsgEntity;
import com.sam.im.heiqun.sound.ChatCallActivity;
import com.sam.im.heiqun.sound.entity.ConstantApp;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.utils.ConversationUtils;
import com.sam.im.heiqun.utils.EventBusTypeData;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

public class CallFriendThreeActivity extends Activity {

    public String CALL_FRIEND_TYPE = "VIDEO", CALL_FRIEND_AGIN_TYPE = "VIDEO"; //callType 通话类型 VOICE 语音通话  VIDEO 视频通话
    private String type;//trequest请求
    private LinearLayout ll_call_callResponse;
    private TextView tv_ca_name;
    private Button btn_canale_video, btn_agree_vido, btn_no_vido;
    private String data, friend_id;
    private ConversationUtils conversationUtils;
    private JSONObject jsonObject;
    private MediaPlayer mPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call_three_friend);
        init();
    }

    public void init() {
        EventBus.getDefault().register(this);
        data = getIntent().getStringExtra("data");

        try {
            jsonObject = new JSONObject(data);
            if (jsonObject == null) return;

        } catch (JSONException e) {
            e.printStackTrace();
        }
        friend_id = getSharedPreferences("Demo", Context.MODE_PRIVATE).getString("friend_ids", null);
        Log.i("fanhui", "friend_id:" + friend_id);
        conversationUtils = new ConversationUtils(this);
        ll_call_callResponse = (LinearLayout) findViewById(R.id.ll_call_callResponse);
        btn_canale_video = (Button) findViewById(R.id.btn_canale_video);
        btn_no_vido = (Button) findViewById(R.id.btn_no_vido);
        btn_agree_vido = (Button) findViewById(R.id.btn_agree_vido);
        tv_ca_name = (TextView) findViewById(R.id.tv_ca_name);
        ll_call_callResponse.setVisibility(View.VISIBLE);
        btn_canale_video.setVisibility(View.GONE);

        try {
            if (jsonObject.getInt("messageType") == Constant.TOMessageTypeVoiceRequest) {
                //发起语音
                tv_ca_name.setText(jsonObject.getString("fromName") + "请求发起语音通话");
            } else {
                tv_ca_name.setText(jsonObject.getString("fromName") + "请求发起视频通话");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        btn_no_vido.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // EventBus.getDefault().post(Constant.TOMessageTypeRefuseVideoRequest);
                try {
                    if (jsonObject.getInt("messageType") == Constant.TOMessageTypeVoiceRequest) {
                        Log.i("fanhui", "id:" + friend_id);
                        //拒接接受语音
                        acceptCall(Constant.TOMessageTypeRefuseVoiceRequest, jsonObject.getInt("fromId"));
                    } else {
                        acceptCall(Constant.TOMessageTypeRefuseVideoRequest, jsonObject.getInt("fromId"));
                    }
                    MsgEntity msgEntity = new MsgEntity();
                    msgEntity.setMsgString(getResources().getString(R.string.chat_cancle_refuse));
                    String msg = new Gson().toJson(msgEntity);

                    conversationUtils.sendMsgTime(msg, ChatRecyclerAdapter.TO_USER_EMOJI_TEXT, jsonObject.getInt("fromId"));

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                finish();
            }
        });
        btn_agree_vido.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //同意接受语音


                Intent intent = new Intent(CallFriendThreeActivity.this, ChatCallActivity.class);

                try {
                    intent.putExtra(ConstantApp.ACTION_KEY_CHANNEL_NAME, jsonObject.getString("content"));
                    intent.putExtra("fromid", jsonObject.getInt("fromId"));
                    intent.putExtra("type", jsonObject.getInt("messageType"));
                    startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //存在
                EventBus.getDefault().post(Constant.TOMessageTypeRefuseVideoRequest);
                try {
                    MsgEntity msgEntity = new MsgEntity();
                    msgEntity.setMsgString(getResources().getString(R.string.chat_time) + ChatCallActivity.getTime(ChatCallActivity.recLen));
                    String msg = new Gson().toJson(msgEntity);
                    if (friend_id == null) return;
                    conversationUtils.sendMsgTime(msg, ChatRecyclerAdapter.TO_USER_EMOJI_TEXT, Integer.parseInt(friend_id));
                    acceptCall(Constant.TOMessageTypeCancleVoiceVideo, Integer.parseInt(friend_id));
                    if (jsonObject.getInt("messageType") == Constant.TOMessageTypeVoiceRequest) {
                        //同意接受语音

                        acceptCall(Constant.TOMessageTypeAgreeVoiceRequest, jsonObject.getInt("fromId"));
                    } else {
                        acceptCall(Constant.TOMessageTypeAgreeVideoRequest, jsonObject.getInt("fromId"));
                    }
                    SharedPreferences.Editor editor = getSharedPreferences("Demo", Context.MODE_PRIVATE).edit();
                    editor.putString("friend_ids", jsonObject.getInt("fromId") + "");
                    editor.commit();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                finish();
            }
        });
        mPlayer = MediaPlayer.create(this, R.raw.music_callin);
        mPlayer.start();
    }

    /**
     * 同意拒绝音频
     *
     * @param type
     */
    public void acceptCall(int type, int fid) {
        mPlayer.stop();
        try {

            conversationUtils = new ConversationUtils(CallFriendThreeActivity.this);

            conversationUtils.sendMsg(jsonObject.getString("content"), type, fid);
            mPlayer.stop();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onBaseEvent(final EventBusTypeData type) {
        mPlayer.stop();
        if (type.getType() == Constant.TOVIDEOTHREECALL) {
            try {
                JSONObject object = new JSONObject(type.getMsg());
                if (object.getInt("fromId") == jsonObject.getInt("fromId")){
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onBaseEvent(final Integer type) {
        mPlayer.stop();
        if (type == Constant.TOMessageTypeRefuseVideoRequest) {

            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            try {
                if (jsonObject.getInt("messageType") == Constant.TOMessageTypeVoiceRequest) {
                    //拒接接受语音
                    acceptCall(Constant.TOMessageTypeRefuseVoiceRequest, jsonObject.getInt("fromId"));
                } else {
                    acceptCall(Constant.TOMessageTypeRefuseVideoRequest, jsonObject.getInt("fromId"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            mPlayer.stop();
            finish();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }
}
